<template>
  <div class="container">
    <page-header 
      title="违章记录" 
      subtitle="管理所有车辆的违章记录"
    >
      <template #actions>
        <el-button type="primary" @click="handleAdd" class="btn-with-icon">
          <el-icon class="mr-1"><Plus /></el-icon>新增违章记录
        </el-button>
        <el-button type="success" @click="exportData" class="btn-with-icon">
          <el-icon class="mr-1"><Download /></el-icon>导出数据
        </el-button>
      </template>
    </page-header>
    
    <el-card shadow="hover" class="mb-6 card-with-hover">
      <table-toolbar
        search-placeholder="搜索车牌号/驾驶员/违章地点"
        @search="handleSearch"
        @refresh="resetQuery"
      >
        <template #filters>
          <el-select
            v-model="queryParams.status"
            placeholder="处理状态"
            clearable
            @change="fetchData"
            style="width: 160px"
            class="status-select"
          >
            <el-option 
              v-for="item in VIOLATION_STATUS_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="fetchData"
            style="width: 260px"
            class="date-picker"
          />
        </template>
        
        <template #actions>
          <el-button type="primary" @click="fetchData" :loading="loading" class="search-btn">
            <el-icon class="mr-1"><Search /></el-icon>查询
          </el-button>
        </template>
      </table-toolbar>
    </el-card>
    
    <el-card shadow="hover" class="overflow-hidden card-with-hover">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :header-cell-class-name="'bg-gray-100 dark:bg-gray-700'"
        class="custom-table"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="plateNumber" label="车牌号" width="120" />
        <el-table-column prop="driver" label="驾驶员" width="100" />
        <el-table-column prop="violationDate" label="违章时间" width="160" />
        <el-table-column prop="violationType" label="违章类型" width="150" />
        <el-table-column prop="location" label="违章地点" width="180" show-overflow-tooltip />
        <el-table-column prop="points" label="扣分" width="80" align="center" />
        <el-table-column prop="fine" label="罚款(元)" width="100" align="center">
          <template #default="{ row }">
            {{ row.fine.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              effect="light"
              class="status-tag"
            >
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handlingPerson" label="经办人" width="120" />
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div class="flex gap-1">
              <el-button 
                type="primary" 
                size="small"
                @click="handleEdit(row)"
                class="edit-btn"
              >
                <el-icon class="mr-1"><Edit /></el-icon>编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="handleDelete(row)"
                class="delete-btn"
              >
                <el-icon class="mr-1"><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container mt-4 flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="DEFAULT_PAGE_SIZES"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增违章记录' : '编辑违章记录'"
      width="580px"
      destroy-on-close
      class="custom-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
        class="form-container"
      >
        <el-form-item label="车牌号" prop="plateNumber">
          <el-select
            v-model="form.plateNumber"
            placeholder="请选择车牌号"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in vehicleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="驾驶员" prop="driver">
          <el-select
            v-model="form.driver"
            placeholder="请选择驾驶员"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in driverOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="违章时间" prop="violationDate">
          <el-date-picker
            v-model="form.violationDate"
            type="datetime"
            placeholder="请选择违章时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="违章类型" prop="violationType">
          <el-input v-model="form.violationType" placeholder="请输入违章类型" />
        </el-form-item>
        
        <el-form-item label="违章地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入违章地点" />
        </el-form-item>
        
        <el-form-item label="扣分" prop="points">
          <el-input-number 
            v-model="form.points" 
            :min="0" 
            :max="12"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="罚款(元)" prop="fine">
          <el-input-number 
            v-model="form.fine" 
            :min="0" 
            :step="50"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="form.status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in VIOLATION_STATUS_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="经办人" prop="handlingPerson">
          <el-input v-model="form.handlingPerson" placeholder="请输入经办人" />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search, Edit, Delete } from '@element-plus/icons-vue'
import PageHeader from '@/components/PageHeader.vue'
import TableToolbar from '@/components/TableToolbar.vue'
import { violationApi, vehicleApi, driverApi } from '@/api'
import { DEFAULT_PAGE_SIZE, DEFAULT_PAGE_SIZES, VIOLATION_STATUS, VIOLATION_STATUS_OPTIONS } from '@/utils/constants'
import { violationRules } from '@/utils/formRules'

export default {
  name: 'ViolationPage',
  components: {
    PageHeader,
    TableToolbar,
    Plus,
    Download,
    Search,
    Edit,
    Delete
  },
  setup() {
    // 表格数据
    const tableData = ref([])
    const loading = ref(false)
    
    // 分页
    const currentPage = ref(1)
    const pageSize = ref(DEFAULT_PAGE_SIZE)
    const total = ref(0)
    
    // 查询参数
    const queryParams = reactive({
      keyword: '',
      status: '',
      dateRange: []
    })
    
    // 对话框
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const formRef = ref(null)
    const submitLoading = ref(false)
    
    // 表单
    const form = reactive({
      id: null,
      plateNumber: '',
      driver: '',
      violationDate: '',
      violationType: '',
      location: '',
      points: 0,
      fine: 0,
      status: '',
      handlingPerson: '',
      remark: ''
    })
    
    // 选项数据
    const vehicleOptions = ref([])
    const driverOptions = ref([])
    
    // 验证规则
    const rules = violationRules
    
    // 获取违章记录列表
    const fetchData = async () => {
      loading.value = true
      try {
        // 实际项目中应从API获取
        /*
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          keyword: queryParams.keyword,
          status: queryParams.status,
          startDate: queryParams.dateRange[0],
          endDate: queryParams.dateRange[1]
        }
        const { data } = await violationApi.getList(params)
        tableData.value = data.records
        total.value = data.total
        */
        
        // 模拟数据
        await new Promise(resolve => setTimeout(resolve, 500))
        
        const mockData = [
          {
            id: 1,
            plateNumber: '京A12345',
            driver: '张三',
            violationDate: '2023-03-15 10:30:00',
            violationType: '闯红灯',
            location: '北京市海淀区中关村大街',
            points: 6,
            fine: 200,
            status: 'pending',
            handlingPerson: '',
            remark: ''
          },
          {
            id: 2,
            plateNumber: '京B67890',
            driver: '李四',
            violationDate: '2023-03-10 14:45:00',
            violationType: '违规停车',
            location: '北京市朝阳区建国路',
            points: 3,
            fine: 150,
            status: 'processing',
            handlingPerson: '王总监',
            remark: '处理中'
          },
          {
            id: 3,
            plateNumber: '京C13579',
            driver: '王五',
            violationDate: '2023-02-28 08:15:00',
            violationType: '超速行驶',
            location: '北京市丰台区六里桥',
            points: 9,
            fine: 350,
            status: 'completed',
            handlingPerson: '李经理',
            remark: '罚款已缴纳'
          }
        ]
        
        // 模拟搜索过滤
        let filteredData = [...mockData]
        
        if (queryParams.keyword) {
          const keyword = queryParams.keyword.toLowerCase()
          filteredData = filteredData.filter(item => 
            item.plateNumber.toLowerCase().includes(keyword) ||
            item.driver.toLowerCase().includes(keyword) ||
            item.location.toLowerCase().includes(keyword)
          )
        }
        
        if (queryParams.status) {
          filteredData = filteredData.filter(item => item.status === queryParams.status)
        }
        
        if (queryParams.dateRange && queryParams.dateRange.length === 2) {
          const startDate = new Date(queryParams.dateRange[0]).getTime()
          const endDate = new Date(queryParams.dateRange[1] + ' 23:59:59').getTime()
          
          filteredData = filteredData.filter(item => {
            const itemDate = new Date(item.violationDate).getTime()
            return itemDate >= startDate && itemDate <= endDate
          })
        }
        
        tableData.value = filteredData
        total.value = filteredData.length
      } catch (error) {
        ElMessage.error('获取违章记录失败')
        console.error('获取违章记录失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 获取车辆和驾驶员数据
    const fetchOptions = async () => {
      try {
        // 模拟数据
        vehicleOptions.value = [
          { value: '京A12345', label: '京A12345' },
          { value: '京B67890', label: '京B67890' },
          { value: '京C13579', label: '京C13579' }
        ]
        
        driverOptions.value = [
          { value: '张三', label: '张三' },
          { value: '李四', label: '李四' },
          { value: '王五', label: '王五' }
        ]
      } catch (error) {
        console.error('获取选项数据失败:', error)
      }
    }
    
    // 搜索处理
    const handleSearch = (value) => {
      queryParams.keyword = value
      currentPage.value = 1
      fetchData()
    }
    
    // 重置查询
    const resetQuery = () => {
      queryParams.keyword = ''
      queryParams.status = ''
      queryParams.dateRange = []
      fetchData()
    }
    
    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchData()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchData()
    }
    
    // 新增违章记录
    const handleAdd = () => {
      dialogType.value = 'add'
      Object.keys(form).forEach(key => {
        if (key === 'points') form[key] = 0
        else if (key === 'fine') form[key] = 0
        else if (key === 'violationDate') form[key] = new Date()
        else if (key === 'status') form[key] = 'pending'
        else form[key] = ''
      })
      dialogVisible.value = true
      
      // 等待DOM更新后重置表单验证
      setTimeout(() => {
        formRef.value && formRef.value.clearValidate()
      }, 0)
    }
    
    // 编辑违章记录
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      Object.assign(form, row)
      dialogVisible.value = true
      
      // 等待DOM更新后重置表单验证
      setTimeout(() => {
        formRef.value && formRef.value.clearValidate()
      }, 0)
    }
    
    // 删除违章记录
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除车牌号为"${row.plateNumber}"的违章记录吗？此操作不可恢复！`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          // 实际项目中应调用API
          // await violationApi.delete(row.id)
          
          ElMessage.success('删除违章记录成功')
          fetchData()
        } catch (error) {
          ElMessage.error('删除违章记录失败')
          console.error('删除违章记录失败:', error)
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid, fields) => {
        if (valid) {
          submitLoading.value = true
          try {
            // 实际项目中应调用API
            /*
            if (dialogType.value === 'add') {
              await violationApi.create(form)
            } else {
              await violationApi.update(form.id, form)
            }
            */
            
            // 模拟API延迟
            await new Promise(resolve => setTimeout(resolve, 500))
            
            ElMessage.success(dialogType.value === 'add' ? '新增违章记录成功' : '编辑违章记录成功')
            dialogVisible.value = false
            fetchData()
          } catch (error) {
            ElMessage.error(dialogType.value === 'add' ? '新增违章记录失败' : '编辑违章记录失败')
            console.error('提交表单失败:', error)
          } finally {
            submitLoading.value = false
          }
        } else {
          console.error('表单验证失败:', fields)
        }
      })
    }
    
    // 导出数据
    const exportData = () => {
      ElMessage({
        message: '违章记录导出成功，请在下载中心查看',
        type: 'success',
        duration: 2000
      })
      // 实际项目中应调用导出API
      // window.location.href = '/api/violation/export'
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const types = {
        'pending': 'warning',
        'processing': 'primary',
        'completed': 'success',
        'cancelled': 'info'
      }
      return types[status] || 'info'
    }
    
    // 获取状态标签
    const getStatusLabel = (status) => {
      const option = VIOLATION_STATUS_OPTIONS.find(item => item.value === status)
      return option ? option.label : status
    }
    
    // 初始化
    onMounted(() => {
      fetchData()
      fetchOptions()
    })
    
    return {
      tableData,
      loading,
      currentPage,
      pageSize,
      total,
      DEFAULT_PAGE_SIZES,
      queryParams,
      dialogVisible,
      dialogType,
      form,
      formRef,
      rules,
      submitLoading,
      vehicleOptions,
      driverOptions,
      VIOLATION_STATUS_OPTIONS,
      fetchData,
      handleSearch,
      resetQuery,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleDelete,
      submitForm,
      exportData,
      getStatusType,
      getStatusLabel
    }
  }
}
</script>

<style scoped>
.el-table :deep(.el-table__header) th {
  font-weight: 600;
}

.el-card {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 8px;
}

.card-with-hover:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.status-tag {
  min-width: 70px;
  text-align: center;
  font-weight: 500;
  border-radius: 4px;
  transition: all 0.3s;
}

.btn-with-icon {
  display: flex;
  align-items: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.btn-with-icon:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
}

.custom-pagination {
  margin-top: 16px;
}

.custom-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding: 16px 20px;
}

.custom-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #eee;
  padding: 16px 20px;
}

.date-picker {
  transition: all 0.3s;
}

.date-picker:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 编辑和删除按钮样式 */
.edit-btn, .delete-btn {
  transition: all 0.3s;
}

.edit-btn:hover, .delete-btn:hover {
  transform: translateY(-2px);
}

.edit-btn:hover {
  background-color: var(--el-color-primary-light-3);
}

.delete-btn:hover {
  background-color: var(--el-color-danger-light-3);
}

/* 表格行样式 */
:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: var(--el-color-primary-light-9) !important;
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 修复暗黑模式下的表格样式 */
:deep(.dark-theme .el-table) {
  --el-table-border-color: var(--border-color);
  --el-table-header-bg-color: var(--bg-color);
}

/* 暗黑模式下的卡片悬浮效果 */
:deep(.dark-theme .card-with-hover:hover) {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
}

/* 搜索和过滤组件样式 */
.el-input, .el-select, .el-date-picker {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}
</style> 